<template>
    <div class="box">
        <header class="header">
            <van-nav-bar
                :title="totalNum > 0 ? '购物车(' + totalNum + ')' : '购物车'"
                left-text="返回"
                left-arrow
                @click-left="$router.push('/home')"
            />
        </header>
        <div class="content">
          <van-empty description="购物车空空如也" v-if="empty" image="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fi01.c.aliimg.com%2Fimg%2Fibank%2F2015%2F153%2F233%2F2040332351_1641646393.310x310.jpg&refer=http%3A%2F%2Fi01.c.aliimg.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1633863616&t=1efa0c4422d0fecad881bafa3cf2a000">
            <van-button round type="danger" class="bottom-button" @click="$router.push('/home')">首页</van-button>
          </van-empty>
            <div class="hasShop" v-else>
                    <van-swipe-cell v-for="item in cartList" :key='item.proid'>
                        <van-row>
                            <van-col span="2">
                                <van-checkbox v-model="item.flag" @click="selectOneFn(item.cartid, item.flag)"></van-checkbox>
                            </van-col>
                            <van-col span="22">
                                <van-card
                                    :price="item.originprice"
                                    :title="item.proname"
                                    class="goods-card"
                                    :thumb="item.img1">
                                    <template #num>
                                        <van-stepper @change="updateNumFn(item.cartid, item.num)" v-model="item.num" theme="round" button-size="22" disable-input></van-stepper>
                                    </template>
                                </van-card>
                            </van-col>
                        </van-row>
                        <template #right>
                            <van-button square text="删除" type="danger" class="delete-button" @click='remove(item.cartid)'/>
                        </template>
                    </van-swipe-cell>
                    <van-submit-bar :price="totalPrice" button-text="提交订单" :disabled="totalNum === 0" @submit="$router.push({ name:'order', params: { addressid:' ' } })">
                      <van-checkbox v-model="checked" @click="selectAllFn">全选</van-checkbox>
                    </van-submit-bar>
            </div>
            <van-divider
              :style="{ color: 'black', borderColor: 'black', padding: '0 16px' }"
            >
              猜你喜欢
            </van-divider>
            <listPage :proList1="recommendList1"/>
        </div>
        <!-- <van-submit-bar :price="3050" button-text="提交订单" @submit="onSubmit">
            <van-checkbox v-model="checked">全选</van-checkbox> -->
    </div>
</template>

<script>
import Vue from 'vue'
import { Divider, Col, Row, Empty, Checkbox, CheckboxGroup, SubmitBar, SwipeCell, Stepper, Tag, Button, NavBar, Card } from 'vant'
import { cartRemove, cartList, updateNum, selectAll, selectOne, recommendList } from '../../api/cart'
import listPage from '../../components/listPage.vue'
import { mapState, mapMutations } from 'vuex'

Vue.use(Divider)
Vue.use(Col)
Vue.use(Row)
Vue.use(Empty)
Vue.use(Checkbox)
Vue.use(CheckboxGroup)
Vue.use(SubmitBar)
Vue.use(SwipeCell)
Vue.use(Stepper)
Vue.use(Tag)
Vue.use(Button)
Vue.use(NavBar)
Vue.use(Card)

export default {
  components: {
    listPage
  },
  data () {
    return {
      num: 0, //购物车数量
      empty: false,
      checked: false,
      cartList: [],
      recommendList1: []
    }
  },
  computed: {

    // 7、计算总价和总数量
    totalNum () {
      return this.cartList.reduce((sum, item) => {
        return item.flag ? sum + item.num : sum + 0
      }, 0)
    },
    totalPrice () {
      return this.cartList.reduce((sum, item) => {
        return item.flag ? sum + item.originprice * item.num : sum + 0
      }, 0) * 100
    }
  },
  methods: {
    //  6、更新当前购物车的选择状态
    selectOneFn (cartid, flag) {
      selectOne({ cartid, flag }).then(res => {
        // console.log(res)
        this.getCartList()
      })
    },
    // 5、更新所有购物车数据的选中状态
    selectAllFn () {
      selectAll({
        userid: localStorage.getItem('userid'),
        type: this.checked
      }).then(res => {
        // console.log(res)
        this.getCartList()
      })
    },
    // 4、更新购物车数量
    updateNumFn (cartid, num) {
      updateNum({ cartid, num }).then(res => {
        // console.log(res)
        this.getCartList()
      })
    },
    // 2、封装渲染购物车函数
    getCartList () {
      cartList({ userid: localStorage.getItem('userid') }).then(res => {
        //  先判断购物车内是否有数据， else 如果有数据 购物车显示，且渲染数据
        // console.log(res.data.data)
        if (res.data.code === '10020') {
          this.empty = true
          this.cartList = []
        } else {
          this.empty = false
          this.cartList = res.data.data
          this.checked = this.cartList.every(item => item.flag)
          res.data.data.forEach(item => {
            this.num += item.num
          })
        }
      })
    },
    // 3、每删除一个商品，重新渲染页面
    // 商品勾选的情况下删除，要再执行一边单选
    remove (cartid) {
      cartRemove({ cartid }).then(res => {
        // console.log(1)
        // console.log(res)
        this.getCartList()
      })
    }
  },
  mounted () {
    
    //  1、每进入购物车页面，判断是否登录，已登录渲染购物车数据
    if (localStorage.getItem('isLogin') === 'true') {
      this.getCartList()
    } else {
      this.$router.push('/login')
    }
    //  猜你喜欢
    recommendList().then(res => {
      // console.log(res.data.data);
      this.recommendList1 = res.data.data
    })
  }
}
</script>

<style>
  .goods-card {
    margin: 0;
    background-color:white;
  }
  .delete-button {
    height: 100%;
  }
  .bottom-button {
    width: 160px;
    height: 40px;
  }
  .van-col.van-col--2{
      height:104px;
      display:flex;
      justify-content: center;
      align-items: center;
      background: white;
      box-sizing: border-box;
      padding-left:10px;
  }
</style>
